//
//  HomeViewController.swift
//  Swift-Tools
//
//  Created by gree on 2020/10/22.
//

import UIKit
import RxDataSources
import RxSwift
import RxCocoa

class HomeViewController: CTTableViewController {
    
    lazy var viewModel: HomeViewModel = {
        let vm = HomeViewModel()
        return vm
    }()
    
    var disposedBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "深圳-周星驰"
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            self.configureTableView()
        }
    }
    
    func configureTableView() {
        
        tableView.register(UINib.init(nibName: "DefaultCell", bundle: nil), forCellReuseIdentifier: "DefaultCell")
        
        let dataSources = RxTableViewSectionedReloadDataSource<TableSection<HomeItem>>(configureCell: {ds, tv, ip, item in
            switch ds[ip].type{
                case .defalut:
                    if let cell: DefaultCell = tv.dequeueReusableCell(withIdentifier: "DefaultCell") as? DefaultCell  {
                        cell.titleLab.text = item.title
                        cell.desLab.text = item.descrition
                        
                        return cell
                    }
            }
            return UITableViewCell()
        })
        
        viewModel.sections
            .asObservable()
            .bind(to: tableView.rx.items(dataSource: dataSources))
            .disposed(by: disposedBag)
        
        Observable
            .zip(tableView.rx.modelSelected(HomeItem.self), tableView.rx.itemSelected)
            .subscribe(onNext: { (item, indexPath) in
                switch item.type {
                    case .defalut:
                        self.push(controller: PresentationViewController())
                }
            })
            .disposed(by: disposedBag)
        
    }
}
